package cn.xttc.edu.util;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 发送http请求的工具类
 *
 * @author yl
 */
public class HttpUtils {
    private HttpUtils() {
    }

    /**
     * 1.httpClient发送get请求
     *
     * @param url url地址
     * @return 返回字符串
     */
    public static String sendGet(String url) {
        String result = "";
        CloseableHttpResponse response = null;
        try {
            // 根据地址获取请求,这里发送get请求
            HttpGet request = new HttpGet(url);
            // 获取当前客户端对象
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                // 通过请求对象获取响应对象
                response = httpClient.execute(request);
            }
            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != response) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    /**
     * httpClient发送post请求 携带x-www-form-urlencoded数据格式
     *
     * @param url    地址
     * @param params 参数
     * @return 响应字符串
     */
    public static String doPost(String url, Map<String, String> params) {
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        //配置连接超时时间
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000)
                .setSocketTimeout(5000)
                .setRedirectsEnabled(true)
                .build();
        HttpPost httpPost = new HttpPost(url);
        //设置超时时间
        httpPost.setConfig(requestConfig);

        //装配post请求参数
        List<NameValuePair> list = new ArrayList<>();
        for (String key : params.keySet()) {
            list.add(new BasicNameValuePair(key, String.valueOf(params.get(key))));
        }

        try {
            //将参数进行编码为合适的格式,如将键值对编码为param1=value1&param2=value2
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(list, "utf-8");
            httpPost.setEntity(urlEncodedFormEntity);

            //执行 post请求
            CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);
            String strRequest = "";
            if (null != closeableHttpResponse && !"".equals(closeableHttpResponse)) {
                if (closeableHttpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity httpEntity = closeableHttpResponse.getEntity();
                    strRequest = EntityUtils.toString(httpEntity);
                } else {
                    strRequest = "Error Response" + closeableHttpResponse.getStatusLine().getStatusCode();
                }
            }
            return strRequest;

        } catch (ClientProtocolException e) {
            e.printStackTrace();
            return "协议异常";
        } catch (ParseException e) {
            e.printStackTrace();
            return "解析异常";
        } catch (IOException e) {
            e.printStackTrace();
            return "传输异常";
        } finally {
            try {
                if (closeableHttpClient != null) {
                    closeableHttpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }


    /**
     * 3.httpClient发送post请求 携带json数据格式
     *
     * @param url     url
     * @param jsonStr json字符串
     * @return 字符串
     */
    public static String sendPost(String url, String jsonStr) {
        CloseableHttpResponse httpResponse = null;
        String result = "";
        try {
            // 1.创建httpClient
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                // 2.创建post请求方式实例
                HttpPost httpPost = new HttpPost(url);

                // 2.1设置请求头 发送的是json数据格式
                httpPost.setHeader("Content-type", "application/json;charset=utf-8");
                httpPost.setHeader("Connection", "Close");

                // 3.设置参数---设置消息实体 也就是携带的数据
                StringEntity entity = new StringEntity(jsonStr, StandardCharsets.UTF_8);
                // 设置编码格式
                entity.setContentEncoding("UTF-8");
                // 发送Json格式的数据请求
                entity.setContentType("application/json");
                // 把请求消息实体塞进去
                httpPost.setEntity(entity);

                // 4.执行http的post请求
                // 4.执行post请求操作，并拿到结果
                httpResponse = httpClient.execute(httpPost);
            }
            // 获取结果实体
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                result = EntityUtils.toString(httpEntity, "UTF-8");
            } else {
                // 如果httpEntity为空，那么直接消化掉即可
                EntityUtils.consume(null);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != httpResponse) {
                try {
                    httpResponse.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

}
